﻿#include "customthread.h"

namespace Common {

	struct CustomThreadData
	{
		CustomThreadData(const ThreadFunc & func, const string & name) :m_func(func), m_threadName(name) {
		}

		ThreadFunc m_func;
		string m_threadName;

		void runInThread() {
			try {
				m_func();
			}
			catch (...) {
				cout << "unprocess exception~" << endl;
			}
		}
	};

	void startInThread(void * obj)
	{
		CustomThreadData * data = static_cast<CustomThreadData *>(obj);
		data->runInThread();
		delete data;
	}

	CustomThread::CustomThread(const ThreadFunc func, const string &tname) :m_func(func), m_threadName(tname), m_started(false)
	{

	}

	CustomThread::~CustomThread()
	{
		join();
		cout << "destructor rthread~~" << endl;
	}

	void CustomThread::start()
	{
		CustomThreadData * t_data = new CustomThreadData(m_func, m_threadName);
		m_thread = std::move(std::thread(startInThread, t_data));
		m_started = true;
	}

	void CustomThread::join()
	{
		if (m_thread.joinable())
			m_thread.join();
	}

	bool CustomThread::joinable()
	{
		return m_thread.joinable();
	}

} //namespace Common
